import {ref, onUnmounted, computed} from "vue";
import dayjs from "dayjs";

export function countDown(callback: Function) {
    //存放时间的变量
    let time: any = ref(null);
    //计时器变量
    let timer: any = null;
    //格式化时间
    let formatTime = computed(() => {
        return dayjs.unix(time.value).format('mm:ss');
    })

    //开始倒计时
    function startCountDown(duration: number) {
        time.value = duration;
        timer = setInterval(() => {
            time.value--;
            if (time.value <= 0) {
                callback();
                clearInterval(timer);
                return;
            }
        }, 1000)
    }

    onUnmounted(() => {
        clearInterval(timer);
    })

    return {
        formatTime,
        startCountDown
    }

}